package com.sgb.kjwl.viewmodel.self.carMakers;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.net.LogisticsNet;
import com.sgb.kjwl.model.entity.transport.InvoiceRateEntity;
import com.sgb.kjwl.view.ui.activity.transport.CarriageDetailActivity;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.map.CargoMapEntity;
import com.sgb.kjwl.model.entity.self.CarriagePushEntity;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.swgk.core.util.UserOperating;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.net.util.RequestUtil;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.NumberUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

public class CarriageInfoPublishModel extends AndroidViewModel {

    //承运类型
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldType = new MutableLiveData<>();
    //车辆信息
    public MutableLiveData<List<CarInfo>> ldCar = new MutableLiveData<>();
    public MutableLiveData<List<CarInfo>> ldRefreshCar = new MutableLiveData<>();
    //承运详情数据
    public MutableLiveData<CarriagePushEntity> ldDetail = new MutableLiveData<>();
    //发布成功回调
    public MutableLiveData<Boolean> ldPush = new MutableLiveData<>();
    //是否是地图发布货源
    private boolean mIsMapRelease;
    //发票
    public MutableLiveData<List<InvoiceRateEntity>> ldInvoiceRateEntity = new MutableLiveData<>();

    public CarriageInfoPublishModel(Application application) {
        super(application);
    }

    /**
     * 承运类型
     */
    public void getCarriageType() {
        List<GoodsInfoTypeEntity3> list = new ArrayList<>();
        list.add(new GoodsInfoTypeEntity3("1", "找货承运"));
        list.add(new GoodsInfoTypeEntity3("3", "返程货运"));
        list.add(new GoodsInfoTypeEntity3("2", "竞价找货"));
        ldType.postValue(list);
    }

    /**
     * 获取用户车辆信息
     */
    public void getCarInfo(Context context, boolean isNeedRefresh) {
        DialogHelper.showProgressDialog(context, "请求中...");
        NewAPIManager.getInstance().getLogisticsAPI().getCarInfo().enqueue(new ICallBack<BaseEntity<List<CarInfo>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CarInfo>> data) {
                if (isNeedRefresh) {
                    ldRefreshCar.postValue(data.getData());
                } else {
                    ldCar.postValue(data.getData());
                }
            }
        });
    }

    /**
     * 获取承运详情
     */
    public void getCarriageDetail(Context context, String no, boolean isHistory) {
        DialogHelper.showProgressDialog(context, "请求中...");
        NewAPIManager.getInstance().getLogisticsAPI().getPushCarriageDetail(no).enqueue(new ICallBack<BaseEntity<CarriagePushEntity>>() {
            @Override
            public void onSuccess(BaseEntity<CarriagePushEntity> data) {
                CarriagePushEntity entity = data.getData();
                dealData(entity, isHistory);
            }

            @Override
            public void onFailure(Call<BaseEntity<CarriagePushEntity>> call, Throwable t) {
                super.onFailure(call, t);
                ldDetail.postValue(null);
            }
        });
    }

    /**
     * 处理承运数据
     */
    private void dealData(CarriagePushEntity entity, boolean isHistory) {
        //编辑时选择历史数据组装原no数据
        if (isHistory) {
            if (ldDetail.getValue() != null && !TextUtils.isEmpty(ldDetail.getValue().getNo())) {
                entity.setId(ldDetail.getValue().getId());
                entity.setNo(ldDetail.getValue().getNo());
            } else {
                entity.setId("");
                entity.setNo("");
            }
        }
        //装货时间
        long currentTime = DateUtils.getCustomizeDayMorning(0, System.currentTimeMillis()).getTime();
        long beginTime = NumberUtil.convertToLong(entity.getShipmentStartTime());
        //装货开始时间大于当前时间则填入数据
        if (beginTime < currentTime) {
            entity.setShipmentStartTime("");
            entity.setEndTime("");
        }
        ldDetail.postValue(entity);
    }

    /**
     * 组装地图传值数据
     */
    public void assemblyMapData(CargoMapEntity old) {
        mIsMapRelease = true;
        //组装数据
        CarriagePushEntity entity = new CarriagePushEntity();
        entity.setContacts(UserOperating.getInstance().getUserRealName());
        entity.setContactsNumber(UserOperating.getInstance().getPhone());
        //默认选中趟
        entity.setFreightUnit(CargoPublishEntity.FreightMode.MODE_ONCE);
        //设置装卸地
        CargoPublishEntity.LocationEntity send = old.getSendLocation();
        if (send != null && send.getLatitude() != 0 && send.getLongitude() != 0) {
            entity.setLat(send.getLatitude());
            entity.setLng(send.getLongitude());
            entity.setProvinceNo(send.getProvinceNo());
            entity.setProvinceName(send.getProvince());
            entity.setCityNo(send.getCityNo());
            entity.setCityName(send.getCity());
            entity.setDistrictNo(send.getDistrictNo());
            entity.setDistrictName(send.getDistrict());
            entity.setDetailAddress(send.getAddress());
        }
        CargoPublishEntity.LocationEntity dest = old.getDestLocation();
        if (dest != null && dest.getLatitude() != 0 && dest.getLongitude() != 0) {
            entity.setDestLat(dest.getLatitude());
            entity.setDestLng(dest.getLongitude());
            entity.setDestProvinceName(dest.getProvince());
            entity.setDestProvinceNo(dest.getProvince());
            entity.setDestCityNo(dest.getCityNo());
            entity.setDestCityName(dest.getCity());
            entity.setDestDistrictNo(dest.getDistrictNo());
            entity.setDestDistrictName(dest.getDistrict());
            entity.setDestDetailAddress(dest.getAddress());
        }
        ldDetail.postValue(entity);
    }

    /**
     * 推送承运
     */
    public void pushCarriage(Context context, CarriagePushEntity entity) {
        if (entity.getCarrierType() == null) {
            MToast.showToast(getApplication(), "请选择承运类型");
            return;
        }
        if (TextUtils.isEmpty(entity.getCarNumber())) {
            MToast.showToast(getApplication(), "请选择车辆");
            return;
        }
        if (TextUtils.isEmpty(entity.getCityName())) {
            MToast.showToast(getApplication(), "请选择装货地");
            return;
        }
        if (TextUtils.isEmpty(entity.getDestCityName())) {
            MToast.showToast(getApplication(), "请选择货运方向");
            return;
        }
        if(TextUtils.isEmpty(entity.getHaulDistance())){
            MToast.showToast(getApplication(), "请输入运距要求");
            return;
        }
        if (TextUtils.isEmpty(entity.getShipmentStartTime())) {
            MToast.showToast(getApplication(), "请选择装货开始时间");
            return;
        }
        if (TextUtils.isEmpty(entity.getShipmentEndTime())) {
            MToast.showToast(getApplication(), "请选择装货结束时间");
            return;
        }
        if (NumberUtil.convertToLong(entity.getShipmentStartTime()) >= NumberUtil.convertToLong(entity.getShipmentEndTime())) {
            MToast.showToast(getApplication(), "装货结束时间要大于装货开始时间");
            return;
        }
        if(entity.getDiscuss()==0) {
            if (TextUtils.isEmpty(entity.getKilometre())) {
                MToast.showToast(getApplication(), "请输入公里数");
                return;
            }
            if (TextUtils.isEmpty(entity.getFreight())) {
                MToast.showToast(getApplication(), "请输入费用");
                return;
            }
        }

        if(entity.getInvoice() == null){
            MToast.showToast(getApplication(), "请选择发票方式");
            return;
        }

        if (TextUtils.isEmpty(entity.getContacts())) {
            MToast.showToast(getApplication(), "请输入联系人");
            return;
        }
        if (TextUtils.isEmpty(entity.getContactsNumber())) {
            MToast.showToast(getApplication(), "请输入联系电话");
            return;
        } else if (!CheckUtils.checkPhone(entity.getContactsNumber())) {
            MToast.showToast(getApplication(), "请输入正确格式的联系电话");
            return;
        }
        //todo 组装数据
        RequestUtil requestUtil = RequestUtil.map();
        if (!TextUtils.isEmpty(entity.getNo())) {
            requestUtil.add("id", entity.getId());
            requestUtil.add("carrierNo", entity.getNo());
        }
        requestUtil.add("driverNo", entity.getDriverNo());
        requestUtil.add("freightUnit", entity.getFreightUnit());
        requestUtil.add("carNumber", entity.getCarNumber());
        requestUtil.add("carTypeNo", entity.getCarTypeNo());
        requestUtil.add("carLenNo", entity.getCarLenNo());
        requestUtil.add("weight", entity.getWeight());
        requestUtil.add("isDump", entity.getIsDump());
        requestUtil.add("heightHurdle", entity.getHeightHurdle());
        requestUtil.add("provinceName", entity.getProvinceName());
        requestUtil.add("provinceNo", entity.getProvinceNo());
        requestUtil.add("cityName", entity.getCityName());
        requestUtil.add("cityNo", entity.getCityNo());
        requestUtil.add("districtName", entity.getDistrictName());
        requestUtil.add("districtNo", entity.getDistrictNo());
        if (entity.getLat() != 0) {
            requestUtil.add("lat", entity.getLat());
            requestUtil.add("lng", entity.getLng());
        }
        requestUtil.add("detailAddress", entity.getDetailAddress());
        requestUtil.add("destProvinceName", entity.getDestProvinceName());
        requestUtil.add("destProvinceNo", entity.getDestProvinceNo());
        requestUtil.add("destCityName", entity.getDestCityName());
        requestUtil.add("destCityNo", entity.getDestCityNo());
        requestUtil.add("destDistrictName", entity.getDestDistrictName());
        requestUtil.add("destDistrictNo", entity.getDestDistrictNo());
        requestUtil.add("destDetailAddress", entity.getDestDetailAddress());
        if (entity.getDestLat() != 0) {
            requestUtil.add("destLat", entity.getDestLat());
            requestUtil.add("destLng", entity.getDestLng());
        }
        requestUtil.add("shipmentTime", entity.getShipmentStartTime());
        requestUtil.add("shipmentEndTime", entity.getShipmentEndTime());
        if(!TextUtils.isEmpty(entity.getKilometre())) {
            requestUtil.add("kilometre", entity.getKilometre());
        }
        if(!TextUtils.isEmpty(entity.getFreight())) {
            requestUtil.add("freight", entity.getFreight());
        }
        requestUtil.add("invoiceNo", entity.getInvoiceNo());
        if (entity.getInvoice() != null) {
            requestUtil.add("invoice", entity.getInvoice());
        }
        if (entity.getInvoice() != null) {
            requestUtil.add("invoice", entity.getInvoice());
        }
        if (!TextUtils.isEmpty(entity.getPayType())) {
            requestUtil.add("payType", entity.getPayType());
        }
        if (!TextUtils.isEmpty(entity.getRate())) {
            requestUtil.add("rate", entity.getRate());
        }
        if (entity.getBargain() != null) {
            requestUtil.add("bargain", entity.getBargain());
        }
        if (!TextUtils.isEmpty(entity.getNote())) {
            requestUtil.add("note", entity.getNote());
        }
        requestUtil.add("contrcts", entity.getContacts());
        requestUtil.add("contrctsNumber", entity.getContactsNumber());
        requestUtil.add("isTrue", entity.getIsTrue());
        requestUtil.add("haulDistance",entity.getHaulDistance());
        requestUtil.add("discuss",entity.getDiscuss());
        requestUtil.add("carrierType", entity.getCarrierType());
        requestUtil.add("radius",entity.getRadius());
        DialogHelper.showProgressDialog(context, "请求中...");
        NewAPIManager.getInstance().getLogisticsAPI().pushCarrier(requestUtil.buildMap()).enqueue(new ICallBack<BaseEntity<String>>() {
            @Override
            public void onSuccess(BaseEntity<String> data) {
                //设置承运no
                if (!TextUtils.isEmpty(data.getData())) {
                    entity.setNo(data.getData());
                    //跳转详情
                    CarriageDetailActivity.start(context, entity.getNo(),2);
                }
                //发布成功
                EventBus.getDefault().post(LogisticsEvent.make(EventConstant.EVENT_CARRIAGE_RELEASE_SUCCESS, null));
                //判断地图发布
                if (mIsMapRelease) {
                    setMapResultData(entity);
                }
                ldPush.postValue(true);
                MToast.showToast(getApplication(), "提交成功");
            }

            @Override
            public void onFailure(Call<BaseEntity<String>> call, Throwable t) {
                super.onFailure(call, t);
                ldPush.postValue(false);
                MToast.showToast(getApplication(), "操作失败");
            }
        });
    }

    /**
     * 组装地图返回对象
     */
    private void setMapResultData(CarriagePushEntity entity) {
        CargoMapEntity mapEntity = new CargoMapEntity();
        mapEntity.setNo(entity.getNo());
        CargoPublishEntity.LocationEntity send = new CargoPublishEntity.LocationEntity();
        send.setLatitude(entity.getLat());
        send.setLongitude(entity.getLng());
        send.setProvince(entity.getProvinceName());
        send.setCity(entity.getCityName());
        send.setDistrict(entity.getDistrictName());
        send.setProvinceNo(entity.getProvinceNo());
        send.setCityNo(entity.getCityNo());
        send.setDistrictNo(entity.getDistrictNo());
        send.setAddress(entity.getDetailAddress());
        mapEntity.setSendLocation(send);
        CargoPublishEntity.LocationEntity dest = new CargoPublishEntity.LocationEntity();
        dest.setLatitude(entity.getDestLat());
        dest.setLongitude(entity.getDestLng());
        dest.setProvince(entity.getDestProvinceName());
        dest.setCity(entity.getDestCityName());
        dest.setDistrict(entity.getDestDistrictName());
        dest.setProvinceNo(entity.getDestProvinceNo());
        dest.setCityNo(entity.getDestCityNo());
        dest.setDistrictNo(entity.getDestDistrictNo());
        dest.setAddress(entity.getDestDetailAddress());
        mapEntity.setDestLocation(dest);
        //返回地图数据
        EventBus.getDefault().post(LogisticsEvent.make(EventConstant.EVENT_CARRIAGE_RELEASE_SUCCESS_MAP_DATA, mapEntity));
    }

    /**
     * 获取发票列表信息
     */
    public void getInvoices() {
        NewAPIManager.getInstance().getLogisticsAPI().getInvoiceListInfo().enqueue(new ICallBack<BaseEntity<List<InvoiceRateEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<InvoiceRateEntity>> data) {
                ldInvoiceRateEntity.postValue(data.getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<List<InvoiceRateEntity>>> call, Throwable t) {
                super.onFailure(call, t);
                ldInvoiceRateEntity.postValue(null);
            }
        });
    }
}
